package com.shujia.mapreduce;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class Demo8MapJoin {

    public static class MapJoinMapper extends Mapper<LongWritable, Text, Text, NullWritable> {

        //使用hashmap保存学生信息，以学号作为key，以学生信息作为value
        HashMap<String, String> students = new HashMap<>();

        /**
         * setup：每一个maptask执行一次，在map执行之前执行
         */
        @Override
        protected void setup(Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {

            //在大表关联小表的时候，由于小表比较小，可以直接放在内存中
            //可以在每一个maptask中将小表加载到内存中，在map端进行join

            //获取文件系统的对象
            FileSystem fileSystem = FileSystem.get(context.getConfiguration());

            //学生表比较小，可以将学生表加载到内存
            FSDataInputStream fsDataInputStream = fileSystem.open(new Path("/data/student/students.txt"));

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fsDataInputStream));

            String line;
            while ((line = bufferedReader.readLine()) != null) {

                //获取学生id
                String id = line.split(",")[0];

                //将学生id和学生信息放入students集合中
                students.put(id, line);
            }

        }

        /**
         * map：每一条数据执行一次
         */
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {

            //获取分数表中学生的id
            String id = value.toString().split(",")[0];

            //通过id直接从students集合中获取学生的信息
            String stuInfo = students.get(id);

            //将数据保存到hdfs
            context.write(new Text(value.toString() + "," + stuInfo), NullWritable.get());

        }

    }

    public static void main(String[] args) throws Exception {

        Job job = Job.getInstance();

        job.setJobName("mapjoin");

        //mapjoin不需要reduce，设置reduce数量为0
        job.setNumReduceTasks(0);

        job.setJarByClass(Demo8MapJoin.class);

        job.setMapperClass(MapJoinMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);

        FileInputFormat.addInputPath(job, new Path("/data/score"));

        FileOutputFormat.setOutputPath(job, new Path("/data/mapjoin"));

        job.waitForCompletion(true);

    }
}
